<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/17
 * Time: 13:02
 */

namespace app\storage\service;

use app\storage\common\AppConstant;
use app\storage\common\Template;
use app\storage\model\PurchaseDetailModel;
use app\storage\model\PurchaseModel;
use cmf\controller\AdminBaseController;
use service\excel\ExcelReaderFactory;
use service\k3\K3ReaderFactory;

class PurchaseService extends AdminBaseController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**添加K3订单
     * @param $purchaseId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */

    public function addPurchaseFromK3($purchaseId)
    {
        $purchaseId = strtoupper($purchaseId);//大小写转换
        $purchase = strtolower(str_replace(' ', '', $purchaseId));//去掉空格（因为复制单号的时候常常会多复制空格）
        $words = explode(',', AppConstant::PURCHASE_TITLE);//    通过逗号分割 'poord, qin, ww'
        preg_match('/\w[A-z]+/', $purchase, $arr);//字母串为表头
        if (!in_array($arr[0], $words)) {//如果表头不包含poord, qin, ww
            return ret_template(false, '订单格式不正确');
        }
        $type = $arr[0];
        $type = $type == 'ww' ? 'poord' : $type;//两个抬头，一个是自制，一个是采购，流程上是一样的
        $purchaseK3 = K3ReaderFactory::read($type, $purchaseId);//从K3读取数据入库单数据
        if (empty($purchaseK3)) {
            return ret_template(false, 'K3订单数据为空');
        }

        $purchaseDetailModel = new PurchaseDetailModel();
        $where['purchase_id'] = $purchaseId;
        $where['remark'] = array('neq', 'copy');
        $purchaseDb = $purchaseDetailModel->where($where)->order('reel_id desc')->column('reel_id');//获取数据库入库细表的reel_id列表
        $reelIdK3 = array_column($purchaseK3, 'reel_id');

        if (count($purchaseDb) == count($reelIdK3)) {//如果k3的数据和本地库的细表的数量相等，说明之前已经拉取了数据，数据库没有发生变化
            return ret_template(true, '订单暂无更新');
        }

        if (count($purchaseDb) == 0) {//如果本地库的条数为0，说明这是第一次从K3拉取数据（或者拉取以后又删除了）
            $newReelId = $purchaseK3;
        } else {//否则的话，查看有哪些数据是不一样的，即为更新的数据
            $newReelId = [];
            $diff = array_unique(array_diff($reelIdK3, $purchaseDb));
            foreach ($diff as $item) {
                $key = array_search($item, $reelIdK3);
                $newReelId[] = $purchaseK3[$key];
            }
        }

        $supplierId = $purchaseK3[0]['supplier_id'];//每单入库单都对应多家商家，为什么只确定第一单不为空？大概是历史遗留问题？不过不影响
        $purchase = Template::purchaseTemplate($purchaseId, '', '');//利用模板生成purchase
        foreach ($newReelId as $k => $item) {//遍历生成料站细表数据
            $purDetail[] = [
                'uuid' => create_uuid(),
                'reel_id' => $item['reel_id'],
                'count' => $item['count'],
                'purchase_id' => $item['purchase_id'],
                'supplier_id' => $item['supplier_id'],
                'sub_materiel_id' => $item['sub_materiel_id'],
                'time' => get_current_time(),
                'remark' => ''
            ];
            unset($newReelId[$k]);
        }

        $supplier = SupplierService::create_supplier($supplierId);//首先确保厂商号不为空
        if ($supplier['success'] == false) {
            return $supplier;
        }
        $materielList = array_unique(array_column($purDetail, 'sub_materiel_id'));
        $materiel = MaterielService::create_materiel($materielList);
        if ($materiel['success'] == false) {
            return $materiel;
        }

        $model = new PurchaseModel();
        $model->startTrans();
        $tranPur = $model->insert($purchase, true);
        $tranDetail = true;
        if (!empty($purDetail)) {
            $purchaseDetailModel = new PurchaseDetailModel();
            $tranDetail = $purchaseDetailModel->insertAll($purDetail, true);
        }
        if ($tranPur && $tranDetail) {
            $model->commit();
            $result = ret_template(true, '入库单导入成功');
        } else {
            $model->rollback();
            $result = ret_template(false, '入库单导入失败');
        }
        return $result;
    }


    /**添加excel
     * @return mixed
     */
    public function addPurchaseFromExcel()
    {
        $factory = new ExcelReaderFactory;
        $purchaseExcelService = $factory->read('purchase');
        $checkExcel = $purchaseExcelService->checkExcelConfig();
        if ($checkExcel['success'] === false) {
            return $checkExcel;
        }
        $checkData = $purchaseExcelService->checkData();
        if ($checkData['success'] === false) {
            return $checkData;
        }
        $result = $purchaseExcelService->insertToDb();
        return $result;
    }

}